package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.CommonError;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.CourseTeacherMapper;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseTeacher;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.content.service.CourseTeacherService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 课程-教师关系表 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CourseTeacherServiceImpl extends ServiceImpl<CourseTeacherMapper, CourseTeacher> implements CourseTeacherService {
    private final CourseBaseInfoService courseBaseInfoService;
    @Override
    public List<CourseTeacher> getByCourseId(Long courseId) {
       return lambdaQuery()
               .eq(CourseTeacher::getCourseId,courseId)
               .list();
    }

    @Override
    public CourseTeacher saveCourseTeach(CourseTeacher courseTeacher, Long companyId) {
        CourseBase one = courseBaseInfoService.lambdaQuery()
                .eq(CourseBase::getId, courseTeacher.getCourseId())
                .one();
        if (!one.getCompanyId().equals(companyId)){
            XueChengPlusException.cast(CommonError.COMPANY_ERROR);
        }

        //判断是更新还是添加操作
        Long id;
        if (courseTeacher.getId()==null){
            //添加

            save(courseTeacher);
            CourseTeacher newCourseTeacher =lambdaQuery()
                    .eq(CourseTeacher::getCourseId, courseTeacher.getCourseId())
                    .eq(CourseTeacher::getTeacherName, courseTeacher.getTeacherName())
                    .eq(CourseTeacher::getPosition, courseTeacher.getPosition())
                    .eq(CourseTeacher::getIntroduction, courseTeacher.getIntroduction())
                    .one();
            id=newCourseTeacher.getId();
        }else {
            //更新

            updateById(courseTeacher);
            id=courseTeacher.getId();
        }

        return getById(id);
    }

    @Override
    public void deleteCourseTeacher(Long courseId, Long id, Long companyId) {
        CourseBase one = courseBaseInfoService.lambdaQuery()
                .eq(CourseBase::getId, courseId)
                .one();
        if (!one.getCompanyId().equals(companyId)){
            XueChengPlusException.cast(CommonError.COMPANY_ERROR);
        }

        remove(new LambdaQueryWrapper<CourseTeacher>()
                .eq(CourseTeacher::getCourseId,courseId)
                .eq(CourseTeacher::getId,id));

    }
}
